<template>
  <div class="create-cont"> <BasicForm @register="register" /></div>
</template>

<script setup lang="ts">
  import { onMounted, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { templateFormSchema } from './index.data';
  import { saveWorkItemRight } from '/@/api/flow/workItemProxy';

  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  const emit = defineEmits(['submit']);

  const props = defineProps({
    setModalProps: {
      type: Function,
    },

    closeModal: {
      type: Function,
    },
    allData: {
      type: Object,
      default: () => {},
    },
  });

  let isUpdate = false;
  let pid = '';

  const [register, { setFieldsValue, validate, updateSchema }] = useForm({
    schemas: templateFormSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 11,
    },
    labelWidth: 80,
  });
  // 初始化
  const initForm = () => {
    console.log('props.allData---------------------', props.allData);

    const { data, paramsObj } = props.allData;
    isUpdate = paramsObj?.isUpdate ?? false;
    if (isUpdate) {
      // 编辑
      pid = data.pid;
      const deptids = data.deptIDS.split(',');
      const deptNames = data.deptNameInfo.split(',');
      const deptList = deptids.map((i, x) => ({ name: deptNames[x], id: i }));
      updateSchema({
        field: 'moduleIDList',
        componentProps: {
          mode: 'tag',
        },
      });
      setFieldsValue({
        deptIDS: deptList,
        moduleIDList: [Number(data.moduleID)],
        userID: [{ name: data.userName, id: data.userID }],
      });
    }
  };

  // 提交
  const handleSubmit = async () => {
    const values = await validate();
    // console.log('%c提交', 'color:#c78;font-size:30px;font-weight:bold', values);
    values.userID = values.userID?.[0]?.id;
    values.deptIDS = values.deptIDS.map((i) => i.id)?.toString();
    values.userType = 8;
    if (isUpdate) {
      values.pid = pid;
    }
    //console.log('%c提交222', 'color:#c78;font-size:30px;font-weight:bold', values);
    await saveWorkItemRight(values);
    createMessage.success('操作成功');
    props.closeModal!();
    props.allData?.btnItem.tabFn.reload();
  };

  onMounted(async () => {
    await nextTick();
    initForm();
  });

  props.setModalProps!({ showOkBtn: true });
  emit('submit', handleSubmit);
</script>

<style lang="less" scoped></style>
